import logging
import time
import os
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import datetime

from selenium.webdriver.chrome.webdriver import WebDriver

from utils.driver_utils import get_driver
from utils.mysql_utils import execute_stored_proc,call_stored_procedure


@pytest.fixture(scope='session',autouse=True)
def init_mysql():
    sql_file = os.path.join(os.path.dirname(__file__), './sql', 'CreateWarehousesAndAreas')
    execute_stored_proc(sql_file)
    call_stored_procedure('CreateWarehousesAndAreas')
    logging.info('Testdata创建成功')
    yield
    sql_file = os.path.join(os.path.dirname(__file__), './sql', 'clear')
    execute_stored_proc(sql_file)
    call_stored_procedure('clear')
    logging.info('Testdata删除成功')


@pytest.fixture(scope='function')
def drivers():
    driver=get_driver()
    yield driver
    driver.quit()

# 截图保存目录，与项目中的screenshot目录对应
SCREENSHOT_DIR = "screenshot"

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when == "call" and rep.failed:
        # 遍历测试用例的参数，查找WebDriver实例
        for fixture_name, fixture_value in item.funcargs.items():
            if isinstance(fixture_value, WebDriver):
                driver = fixture_value
                # 确保截图目录存在
                if not os.path.exists(SCREENSHOT_DIR):
                    os.makedirs(SCREENSHOT_DIR)
                # 生成包含时间戳和测试用例名称的截图文件名
                timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
                test_case_name = item.name.replace("/", "_").replace("\\", "_")
                screenshot_name = f"{test_case_name}_{timestamp}.png"
                screenshot_path = os.path.join(SCREENSHOT_DIR, screenshot_name)
                try:
                    # 执行截图操作
                    driver.save_screenshot(screenshot_path)
                    print(f"测试用例 {test_case_name} 执行失败，截图已保存至: {screenshot_path}")
                except Exception as e:
                    print(f"截图失败，错误信息: {e}")
                break












